use crate::protocol::data_schema::DataTrait;
use crate::protocol::type_schema::TypeSchema;
use crate::{abstractions::data::Data, error::ServerError};
use crate::protocol::task::{SymbolicTask, TaskStatus};
use super::{manager::{TaskManager, TASK_MANAGER, TaskStruct}, task::Task};
use rocket::{response::status::BadRequest, serde::json::Json};
use rocket::serde::{Serialize, Deserialize};
use serde_json::Value;
use std::collections::HashMap;
use crate::services::service::{Service, ServiceStatus};

#[get("/tasks/list")]
pub async fn get_tasks() -> Json<HashMap<String, TaskStruct>> {
    let manager = TASK_MANAGER.get().unwrap().lock().await;
    let tasks = manager.get_tasks();
    Json(tasks)
}

#[derive(Debug, Serialize)]
pub struct TaskProgressB {
    pub status: TaskStatus,
    pub progress_percentage: f64,
    pub error_message: Option<String>,
}

#[get("/tasks/<task_id>/progress")]
pub async fn get_task_progress(task_id: &str) -> Result<Json<TaskProgressB>, ServerError> {
    let manager = TASK_MANAGER.get().unwrap().lock().await;
    let taskopt = manager.get_task(task_id);
    if taskopt.is_none() {
        return Err(ServerError::TaskErrorStr("任务不存在"))
    }
    let task = taskopt.unwrap();
    Ok(Json(TaskProgressB {
        status: task.status.clone(),
        progress_percentage: task.progress_percentage,
        error_message: task.error_message.clone(),
    }))
}

#[derive(Debug, Serialize)]
pub struct TaskOpB {
    pub success: bool,
    pub message: String,
}

#[post("/tasks/<task_id>/terminate")]
pub async fn terminate_task(task_id: &str) -> Json<TaskOpB> {
    println!("请求终止任务: {}", task_id);
    let mut manager = TASK_MANAGER.get().unwrap().lock().await;
    
    match manager.get_task_mut(task_id) {
        Some(task) => {
            match task.terminate() {
                Ok(_) => {
                    println!("任务终止成功: {}", task_id);
                    Json(TaskOpB {
                        success: true,
                        message: "任务终止请求已发送".to_string(),
                    })
                },
                Err(e) => {
                    println!("任务终止失败: {}, 错误: {:?}", task_id, e);
                    Json(TaskOpB {
                        success: false,
                        message: "终止任务失败".to_string(),
                    })
                },
            }
        },
        None => {
            println!("终止任务失败，未找到任务: {}", task_id);
            Json(TaskOpB {
                success: false,
                message: format!("未找到任务 ID: {}", task_id),
            })
        },
    }
}

#[derive(Debug, Serialize)]
pub struct TaskResultB {
    pub status: TaskStatus,
    pub created_at: u64,
    pub completed_at: Option<u64>,
    pub error_message: Option<String>,
    pub result: Option<Value>,
}

#[get("/tasks/<task_id>/result")]
pub async fn get_task_result(task_id: &str) -> Result<Json<TaskResultB>, ServerError> {
    let manager = TASK_MANAGER.get().unwrap().lock().await;
    let taskopt = manager.get_task(task_id);
    if taskopt.is_none() {
        return Err(ServerError::TaskErrorStr("任务不存在"))
    }
    let task = taskopt.unwrap();
    match &task.result {
        Some(result) => {
            Ok(Json(TaskResultB {
                status: task.status.clone(),
                created_at: task.created_at,
                completed_at: task.completed_at,
                error_message: None,
                result: Some(result.to_json_less()),
            }))
        }
        None => {
            Ok(Json(TaskResultB {
                status: task.status.clone(),
                created_at: task.created_at,
                completed_at: task.completed_at,
                error_message: task.error_message.clone(),
                result: None,
            }))
        }
    }
}

#[get("/tasks/<task_id>")]
pub async fn get_task(task_id: &str) -> Result<Json<TaskStruct>, ServerError> {
    let manager = TASK_MANAGER.get().unwrap().lock().await;
    let task_opt = manager.get_task(task_id);
    
    if let Some(task) = task_opt {
        Ok(Json(TaskStruct {
            workflow_id: task.workflow_id.clone(),
            id: task.id.clone(),
            name: task.name.clone(),
            service_name: task.service_name.clone(),
            result_addr: task.result_sender_addr.clone(),
            status: task.status.clone(),
            progress_percentage: task.progress_percentage,
            error_message: task.error_message.clone(),
            created_at: task.created_at,
            completed_at: task.completed_at
        }))
    } else {
        Err(ServerError::TaskErrorStr("任务不存在"))
    }
}

#[derive(Debug, Deserialize)]
pub struct CreateTaskRequest {
    pub service_name: String,
    pub task_name: String,
    pub input_data: Value,
}

#[derive(Debug, Serialize)]
pub struct CreateTaskResponse {
    pub task_id: String,
    pub success: bool,
    pub message: Option<String>,
}

#[post("/tasks", data = "<req>")]
pub async fn create_task(req: Json<CreateTaskRequest>) -> Result<Json<CreateTaskResponse>, ServerError> {
    let service_manager = crate::services::manager::SERVICE_MANAGER.get().unwrap().lock().await;
    let service_opt = service_manager.get_service(&req.service_name);
    if service_opt.is_none() {
        return Err(ServerError::TaskErrorStr("服务不存在"));
    }
    let service = service_opt.unwrap();
    drop(service_manager);
    
    let task_sig_opt = service.get_task(&req.task_name);
    if task_sig_opt.is_none() {
        return Err(ServerError::TaskErrorStr("任务不存在于该服务中"));
    }
    let task_sig = task_sig_opt.unwrap();
    
    let input = match serde_json::to_string(&req.input_data) {
        Ok(file_content) => {
            match &task_sig.input_type {
                TypeSchema::Void => Data::DataVoid,
                _ => {
                    Data::from_json_less(req.input_data.clone(), &task_sig.input_type)?
                }
            }
        },
        Err(_) => return Err(ServerError::TaskErrorStr("无法序列化输入数据"))
    };
    
    let task = Task::new(service.address.clone(), service.name.clone(), task_sig.name.clone(), task_sig.input_type.clone(), task_sig.output_type.clone(), service.get_session_key());
    let task_id = task.id.clone();
    match task.start(input).await {
        Err(ServerError::ServiceCannotReach) => {
            let mut service_manager = crate::services::manager::SERVICE_MANAGER.get().unwrap().lock().await;
            service_manager.set_service_status(&service.name, ServiceStatus::CannotReach)?;
            return Err(ServerError::ServiceError(format!("服务连接失败: {}", service.name)));
        }
        _ => {}
    }
    
    Ok(Json(CreateTaskResponse {
        task_id,
        success: true,
        message: None,
    }))
}

pub type LogMessage = String;

pub async fn create_task_func(service: &Service, task_sig: SymbolicTask, file_content: String) -> Result<(), ServerError> {
    let input = match &task_sig.input_type {
        TypeSchema::Void => Data::DataVoid,
        _ => {
            let data_json = serde_json::from_str(&file_content).map_err(|_| ServerError::TaskErrorStr("文件内容不是json格式的"))?;
            Data::from_json_less(data_json, &task_sig.input_type)?
        }
    };
    let task = Task::new(service.address.clone(), service.name.clone(), task_sig.name, task_sig.input_type, task_sig.output_type, service.get_session_key());
    task.start(input).await?;
    Ok(())
}
